<?php
namespace App\Http\Logic;

use App\Models\SwtDheOrder;
use App\Models\SwtDheOrderGoods;

class DheOrderLogic extends BaseLogic
{

    /**
     * @notes 判断是否已存在回调订单
     * @param $out_trade_no
     * @return array|false
     * @author Evil丿
     * @date 2024/07/30 09:43
     */
    public static function hasNotifyOrder($out_trade_no)
    {
        $log_info = SwtDheOrder::with('order') -> firstWhere('out_trade_no', $out_trade_no);

        if(!$log_info) {
            return false;
        }

        return [
            'tradeNo'       => $log_info -> order -> order_sn,
            'outTradeNo'    => $log_info -> out_trade_no,
            'orderStatus'   => $log_info -> order -> is_pay == 0 ? 'NO_PAY' : 'PAY_SUCCESS',
            'totalAmount'   => $log_info -> order -> order_amount,
            'memberNo'      => $log_info -> order -> user_id,
            'paidTime'      => $log_info -> order -> payment_at
        ];
    }
    /**
     * @notes 新增回调订单信息
     * @param $data
     * @return mixed
     * @author Evil丿
     * @date 2024/07/30 09:45
     */
    public static function setNotifyOrder($order_id, $request_id, $data)
    {
        $order_info = [
            'order_id'      => $order_id,
            'request_id'    => $request_id,
            'device_code'   => $data['device_code'],
            'out_trade_no'  => $data['outTradeNo'],
            'attach'        => $data['attach'],
            'desc'          => $data['subject'],
            'notify_url'    => $data['notifyUrl']
        ];

        $res = SwtDheOrder::create($order_info);

        if(!$res) {
            return false;
        }

        if(key_exists('goodsInfos', $data) && is_array($data['goodsInfos'])) {
            foreach($data['goodsInfos'] as $goods) {
                SwtDheOrderGoods::create([
                    'order_id'      => $res -> id,
                    'goods_name'    => $goods['name'],
                    'goods_num'     => $goods['quantity'],
                    'goods_price'   => $goods['amount']
                ]);
            }
        }

        return true;
    }


}
